package org.mg.frontend.bean;

import org.mg.core.entity.Page;
import org.mg.core.service.PageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import java.util.List;

/**
 * @author MG
 * @since 14-04-2013
 */
@ManagedBean
@ViewScoped
public class PageBean {
    private static final Logger logger = LoggerFactory.getLogger(PageBean.class);

    private List<Page> pages;

    private Page selectedPage;

    private int selectedIndex;

    @ManagedProperty(value = "#{pageService}")
    PageService pageService;

    @PostConstruct
    public void init() {
        pages = pageService.getPages();
    }

    public void pageInit() {
        try {
            selectedPage = pageService.getPage(pages.get(selectedIndex).getId());
        } catch (IndexOutOfBoundsException e) {
            logger.warn("Selected page out of bounds: " + e.getMessage());
            selectedPage = new Page();
        }
    }

    public List<Page> getPages() {
        return pages;
    }

    public void setPages(List<Page> pages) {
        this.pages = pages;
    }

    public Page getSelectedPage() {
        return selectedPage;
    }

    public void setSelectedPage(Page selectedPage) {
        this.selectedPage = selectedPage;
    }

    public int getSelectedIndex() {
        return selectedIndex;
    }

    public void setSelectedIndex(int selectedIndex) {
        this.selectedIndex = selectedIndex;
    }

    public void setPageService(PageService pageService) {
        this.pageService = pageService;
    }
}
